﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using libvkontakte;
using System.Threading;

namespace VkontakteChecker.Logic
{
    public class Actions
    {
        public static User _user = new User();
        public static DateTime LastChanged = DateTime.Now;
        private static bool _initializationStatus = false;
        public static bool _isConnectionAvialable = false;
        public static WebProxy proxy = null;


        public static void InitializeUser()
        {
            if (Settings.Email != null && Settings.Password != null)
            {
                _user = new User();
                _user.Email = Settings.Email;
                _user.Password = Settings.Password;
                _initializationStatus = true;
                if(proxy != null)
                {
                    _user.SetProxy(proxy);
                }
            }
        }

        public static bool IsInitializedUser()
        {
            return _initializationStatus;
        }

        public static void CheckConnection()
        {
            Ping ping = new Ping();
            var replay = ping.Send("vkontakte.ru",2000);
            if (replay != null) _isConnectionAvialable = replay.Status == IPStatus.Success;
        }

        public static void LoginUser()
        {
            if (IsInitializedUser() && _isConnectionAvialable)
            {
                _user.Login();
            }
        }

    }

    class ProducerConsumerQueue
    {
        private EventWaitHandle wh = new AutoResetEvent(false);
        private Thread worker;
        private object locker = new object();
        Queue<string> tasks = new Queue<string>();

        public ProducerConsumerQueue()
        {
            worker = new Thread(Work);
            
            worker.Start();
        }

        public void EnqueueTask(string task)
        {
            lock (locker)
                tasks.Enqueue(task);

            wh.Set();
        }

        void Work()
        {
            while (true)
            {
                string task = null;

                lock(locker)
                {
                    if(tasks.Count > 0)
                    {
                        task = tasks.Dequeue();
                        if (task == null)
                            return;
                    }
                }

                if(task != null)
                {
                    System.Media.SystemSounds.Asterisk.Play();
                }
                else
                {
                    wh.WaitOne();
                }
            }
        }
    }

}
